/**
 *  written by ChenLong
 */

(function($){
	
	$("head").append("<link rel='stylesheet' href='/trd/jquery-treeselect/tree-select.css'>");
	
	var tree = function(ele,opt){
		this.$element = ele; 
		this.defaults = {
			multiSelect: false,
			data: [],
			callback: null
	    };
		this.options = $.extend({},this.defaults, opt);
	}
	
	tree.prototype = {
		//初始化	
		init: function(){
			var that = this;
			var html = "<div class='jq-tree-wrapper'>" +
					   	"<input class='form-control jq-tree-select' readonly/>"+
						"<div class='tree-select-backdrop'>" +
							"<div class='ztree'></div>"
						"</div>"+
					   "</div>"
			this.$element.html(html);
			
			var setting = {
			    view: {
			        showLine: true
			    },
			    data: {
			        simpleData: {
			            enable: true,
			            idKey: this.options.idKey,
			            pIdKey: this.options.pIdKey
			        },
			        key: {
			            name: this.options.name
			        },
			    },
			    check: {
			        enable: this.options.multiSelect,
			        chkStyle: "checkbox",
					chkboxType: {
					     "Y": "",
					     "N": ""
					}
			    },
			    callback: {
			    	onClick: function(event, treeId, treeNode){
			    		if(!that.options.multiSelect){
			    			$(".jq-tree-select").val(treeNode[that.options.name]);
				    		that.treeSelectToggleShow();
				    		if(that.options.callback){
				    			that.options.callback(treeNode);
				    		}
			    		}
			    		event.stopPropagation();
			    		return false;
			    	},
			    	onCheck: function(event, treeId, treeNode){
			    		var $input = $(".jq-tree-select");
			    		if(treeNode.checked){
			    			if($input.val() == ''){
				    			$input.val(treeNode[that.options.name]);
				    		}else{
				    			var arr = $input.val().split(",");
				    			arr.push(treeNode[that.options.name]);
				    			$input.val(arr.join(","));
				    		}	
			    		}else{
			    			var arr = $input.val().split(",");
			    			var index = -1;
			    			for(var i = 0;i < arr.length;i++){
			    				if(arr[i] == treeNode[that.options.name]){
			    					index = i;
			    				}
			    			}
			    			if(index > -1){
			    				arr.splice(index,1);
				    			$input.val(arr.join(","));	
			    			}
			    		}
			    		event.stopPropagation();
			    		return false;
			    	}
			    }
			};
			
			var ztreeDom = this.$element.find('.ztree')[0];
			this.$ztree =  $.fn.zTree.init($(ztreeDom), setting, this.options.data);
			
			this.$element.find('.jq-tree-select').click(function(event){
				that.treeSelectToggleShow();
				event.stopPropagation();
	    		return false;
			});
			
			$(".jq-tree-wrapper").click(function(event){
				event.stopPropagation();
	    		return false;
			});
			
			$(window).click(function(event){
				var $el = that.$element.find('.tree-select-backdrop')[0];
				$el.style.display = 'none';
				event.stopPropagation();
	    		return false;
			});
			
			return this;
		},
		//下拉树显示隐藏
		treeSelectToggleShow: function(){
			var $el = this.$element.find('.tree-select-backdrop')[0];
			if($el.style.display === 'none' || $el.style.display === ''){
				$el.style.display = 'block';
			}else{
				$el.style.display = 'none';
			}
			return false;
		},
		//若节点可被选择，则返回目前被选中的节点所组成的数组
		getCheckedNodes: function(){
			if(this.options.multiSelect){
				var nodes = this.$ztree.getCheckedNodes(true);
			}else{
				var nodes = this.$ztree.getSelectedNodes(true);
			}
			return nodes;
		},
		//设置目前勾选的节点
		setCheckedNodes: function(node){
			if(!(nodes instanceof Array)){
				console.log("传入参数非数组！");
				return;
			}
			var that = this;
			var $input = $(".jq-tree-select");
			if(this.options.multiSelect){
				nodes.forEach(function(item){
					var obj = that.$ztree.getNodeByParam(that.options.idKey, item[that.options.idKey], null);
					that.$ztree.checkNode(obj, true, true);
					var arr = [];
					if($input.val() !== ''){
						var arr = $input.val().split(",");
					}
					arr.push(obj[that.options.name]);
	    			$input.val(arr.join(","));
				})
			}else{
				var obj = this.$ztree.getNodeByParam(this.options.idKey, nodes[0][this.options.idKey], null);
	    		this.$ztree.selectNode(obj);
	    		$input.val(node[this.options.name]);
			}
    		return this;
		},
	}
	
	$.fn.treeSelect = function(options){
		
		var treeSelect = new tree(this,options);
		
		return treeSelect.init();
	}
	
})(jQuery)